<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {Editor, Toolbar} from "@wangeditor/editor-for-vue";
import  {type IDomEditor, type IEditorConfig, type IToolbarConfig} from "@wangeditor/editor"
import {upload} from "@/apis/common";


const {modelValue} =defineProps<{
  modelValue?: string | undefined
}>()

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

const emit = defineEmits<{
  (e: 'update:modelValue', val: string): void
}>()
// 内容 HTML
const valueHtml = computed({
  get(){
    return modelValue
  },
  set(val){
    emit('update:modelValue', val)
  }
})

const toolbarConfig:Partial<IToolbarConfig> = {}
toolbarConfig.excludeKeys = [
  'fullScreen',
  'group-video'
]

type InsertFnType = (url: string, alt: string, href: string) => void
const editorConfig: Partial<IEditorConfig> = { placeholder: '请输入内容...',MENU_CONF:{
    codeSelectLang:{
      // 代码语言
      codeLangs: [
        { text: 'CSS', value: 'css' },
        { text: 'HTML', value: 'html' },
        { text: 'XML', value: 'xml' },
        { text: 'JavaScript', value: 'javascript'},
        { text: 'Java', value: 'java'},
        { text: 'C++', value: 'cpp'},
        { text: 'C#', value: 'csharp'},
        { text: 'Python', value: 'python'},
        { text: 'Ruby', value: 'ruby'},
        { text: 'PHP', value: 'php'},
        { text: 'Go', value: 'go'},
        // 其他
      ],
    },
    'uploadImage':{
      async customUpload(file: File, insertFn: InsertFnType) {
        const formData = new FormData()
        formData.append('file', file)
        // TS 语法
        const res = await upload(formData)
        insertFn(res.data.data, '', res.data.data)
      },
    }
  }
}



const handleCreated = (editor:IDomEditor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const mode = 'default'


// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<template>
<div class="w-full h-full flex flex-col">
  <Toolbar
    style="border-bottom: 1px solid #ccc"
    :editor="editorRef"
    :defaultConfig="toolbarConfig"
    :mode="mode"
  />
  <Editor
    class="flex-1 overflow-auto"
    v-model="valueHtml"
    :defaultConfig="editorConfig"
    :mode="mode"
    @onCreated="handleCreated"
  />
</div>
</template>

<style scoped>

</style>
